<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addCateDialog = true"> 添加分类</el-button>
        </el-col>
      </el-row>

      <tree-table class="tb-cate" index-text="#" show-index border :data="cateList" :columns="columns" :expand-type="false" :selection-type="false" v-loading="getLoading">
        <template v-slot:isok="{row}">
          <i class="el-icon-success" v-if="!row.deleted" style="color: Green;font-size:14px"></i>
          <i class="el-icon-error" v-else style="color: red;font-size:14px"></i>
        </template>
        <template v-slot:level="{row}">
          <el-tag :type="tagType[row.cat_level]">{{tagText[row.cat_level]}}</el-tag>
        </template>
        <template v-slot:opt="{row}">

          <el-button type="primary" icon="el-icon-edit" size="mini" @click="setCateDialogShow(row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delCate(row)">删除</el-button>
        </template>
      </tree-table>

      <el-pagination @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-size="queryInfo.pagesize" layout="total,prev, pager, next, jumper" :total="queryInfo.total"></el-pagination>
    </el-card>

    <!-- 添加分类的对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialog" width="50%" @close="addCateClosed" prop="addFormRef" :close-on-click-modal="false">
      <!-- 内容主体区域 -->
      <el-form :model="addCateForm" label-width="80px" @keyup.enter.native="addCate()" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model.trim="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="parent">
          <el-cascader v-model="addCateForm.parent" :options="catceOptions" :props="catceProps" style="width:100%" @change="Change" change-on-select clearable></el-cascader>

        </el-form-item>

      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialog = false">取 消</el-button>
        <el-button type="primary" @click="addCate()" :loading="addLoading">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改分类" :visible.sync="setCateDialog" width="50%" @close="setCateDialogClosed" :close-on-click-modal="false" >
      <el-form :model="editForm" @keyup.enter.native="setCate()" ref="setCate" label-width="100px" :rules="setFormRules">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model.trim="editForm.cat_name"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setCateDialog = false">取 消</el-button>
        <el-button type="primary" @click="cateRoles()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import treeTable from 'vue-table-with-tree-grid'
export default {
  data () {
    return {
      tagType: { 0: '', 1: 'success', 2: 'warning' },
      tagText: { 0: '一级', 1: '二级', 2: '三级' },
      cateList: [],
      queryInfo: {
        total: null,
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
        type: [1, 2, 3]
      },
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 表示将当前列定义为模板列
          type: 'template',
          // 表示当前这一列的模板名称
          template: 'isok'

        },
        {
          type: 'template',
          label: '分类级别',
          prop: 'cat_level',
          template: 'level'
        },
        {
          type: 'template',
          label: '操作',
          template: 'opt'
        }
      ],
      getLoading: false,
      addLoading: false,
      addCateDialog: false,
      setCateDialog: false,
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
        parent: []

      },
      catceOptions: [],
      catceProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      addFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      setFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      editForm: { cat_name: '' },
      rowInfo: null
    }
  },

  created () { // 进入页面就开始执行
    this.getUserList()
    this.getparent()
  },

  components: { // 组件
    treeTable
  },

  computed: {// 计算属性是属性调用，而methods是函数调用
  },

  methods: { // 存储方法，处理复杂逻辑

    getUserList () {
      this.getLoading = true
      this.$http.get('categories', { params: this.queryInfo }).then(res => {
        res = res.data

        if (res.meta.status !== 200) {
          return this.$message.error('获取商品分类失败！')
        }
        this.queryInfo.total = res.data.total

        this.cateList = res.data.result
      }).catch(err => {
        this.$message.error(err || '错误')
      }).finally(() => {
        this.getLoading = false
      })
    },

    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    addCate () {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        this.addLoading = true
        this.$http.post('categories', this.addCateForm).then(res => {
          res = res.data
          console.log(res)
          if (res.meta.status !== 201) {
            return this.$message.error('新增分类失败！')
          }
          this.$message.success('新增分类成功！')
          this.getUserList()
          this.addCateDialog = false
        }).catch(err => {
          this.$message.error(err || '错误')
        }).finally(() => {
          this.addLoading = false
        })
      })
    },
    setCateDialogClosed () {
      this.$refs.setCate.resetFields()
    },
    addCateClosed () {
      this.$refs.addFormRef.resetFields()
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
      this.addCateForm.parent = []
    },
    getparent () {
      this.$http.get('categories', { params: { type: [2] } }).then(res => {
        res = res.data
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品分类失败！')
        }
        this.catceOptions = res.data
      }).catch(err => {
        this.$message.error(err || '错误')
      })
    },
    Change (val) {
      if (val[1]) {
        this.addCateForm.cat_pid = val[1]
        this.addCateForm.cat_level = 2
      } else if (val[0]) {
        this.addCateForm.cat_pid = val[0]
        this.addCateForm.cat_level = 1
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    delCate (row) {
      this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        const loding = this.$fullLoading()
        this.$http.delete('/categories/' + row.cat_id).then(res => {
          res = res.data
          if (res.meta.status !== 200) {
            return this.$message.error('删除分类失败！')
          }

          this.$message.success('删除分类成功！')
          // 删除页码最后一项自动翻页
          const totalPage = Math.ceil((this.queryInfo.total - 1) / this.queryInfo.pagesize) // 总页数
          this.queryInfo.pagenum = this.queryInfo.pagenum > totalPage ? totalPage : this.queryInfo.pagenum
          this.queryInfo.pagenum = this.queryInfo.pagenum < 1 ? 1 : this.queryInfo.pagenum
          this.getUserList()
        }).catch(err => {
          this.$message.error(err || '错误')
        }).finally(() => {
          loding.close()
        })
      }).catch(() => {

      })
    },
    setCateDialogShow (row) {
      this.setCateDialog = true
      this.$nextTick(() => {
        this.editForm.cat_name = row.cat_name
        this.rowInfo = row
      })
    },
    cateRoles () {
      this.$refs.setCate.validate(valid => {
        if (!valid) return

        const loding = this.$fullLoading()
        this.$http.put('/categories/' + this.rowInfo.cat_id, this.editForm).then(res => {
          res = res.data
          if (res.meta.status !== 200) {
            return this.$message.error('编辑分类失败！')
          }
          this.$message.success('编辑分类成功！')
          this.setCateDialog = false
          this.getUserList()
        }).catch(err => {
          this.$message.error(err || '错误')
        }).finally(() => {
          loding.close()
        })
      })
    }

  },

  props: []
}
</script>
<style lang='less' scoped>
.tb-cate {
  margin-top: 15px;
  font-size: 12px;
}

/deep/ .zk-table__header-row {
  height: 48px;
  background: #fff;
  font-weight: 100;
}
/deep/ .zk-table__header-cell {
  color: #909399;
  font-weight: bold;
}
/deep/ .zk-table--firstProp-header-inner {
  padding: 6px 12px;
}
</style>
